package com.steakliu.druiddatasource.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

@RestController
public class DataSourceController {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    private static final int CORE_POOL_SIZE = (int) (Runtime.getRuntime().availableProcessors() / (1-0.9)) * 4;
    private static final int MAXIMUM_POOL_SIZE = 400;
    private static final long KEEP_ALIVE_TIME = 3;
    private static final TimeUnit UNIT = TimeUnit.SECONDS;
    private static final LinkedBlockingDeque<Runnable> WORK_QUEUE = new LinkedBlockingDeque<>();
    private static final MyThreadFactory THREAD_FACTORY = new MyThreadFactory("business");
    private static final ThreadPoolExecutor pool =
            new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME, UNIT, WORK_QUEUE, THREAD_FACTORY, new ThreadPoolExecutor.DiscardOldestPolicy());

    @GetMapping("datasource")
    public List<Map<String, Object>> datasource(){
        List<Map<String, Object>> maps = jdbcTemplate.queryForList("SELECT * FROM user");
        return maps;
    }

    @GetMapping("insert")
    public void insert(){
        long start = System.currentTimeMillis();
        for (int i = 0 ; i < 500 ; i++){
            jdbcTemplate.execute("INSERT INTO user(name,sex,address,nation,remark) VALUES("+i+","+i+","+i+","+i+","+i+")");
        }
        long time = System.currentTimeMillis() - start;
        System.out.println(time);
    }

    @GetMapping("insertJdbcBatch")
    public void insertJdbcBatch() throws InterruptedException {
        long start = System.currentTimeMillis();
        CountDownLatch countDownLatch = new CountDownLatch(500);
        for (int i = 0 ; i < 500 ; i++){
            int finalI = i;
            int finalI1 = i;
            int finalI2 = i;
            int finalI3 = i;
            int finalI4 = i;
            pool.submit(() -> {
                jdbcTemplate.execute("INSERT INTO user(name,sex,address,nation,remark) VALUES("+ finalI +","+ finalI1 +","+ finalI2 +","+ finalI3 +","+ finalI4 +")");
                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        long time = System.currentTimeMillis() - start;
        System.out.println(time);
    }
}

